package ntu.metaweb.http;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.HashMap;

import ntu.metaweb.Metaweb;
import ntu.metaweb.XMLMarshaller;
import ntu.metaweb.result.NumberedPageRating;
import ntu.metaweb.storage.WebPageQuery;
import ntu.metaweb.storage.WebPageQueryKey;
import rice.Continuation;
import rice.Continuation.MultiContinuation;
import rice.Continuation.NamedContinuation;
import rice.pastry.Id;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;


@SuppressWarnings("restriction")
public class GetPageRatingBulkHandler implements CommandHandler {
	
	@Override
	public void handleCommand(final HttpExchange exchange,
			final HashMap<String, String> params) throws IOException {
		System.out.println("get page rating bulk");
		final String[] urls = URLDecoder.decode(params.get("url_string"), "UTF-8").split("\\|\\|\\|");
		final String[] urlParams = 
			URLDecoder.decode(params.get("params_string"), "UTF-8").split("\\|\\|\\|");
		final int urlnum = urls.length;
		System.out.println(urlnum);
    MultiContinuation multi = new MultiContinuation(
				new Continuation<Object,Exception>() {
					
					@Override
					public void receiveException(Exception exception) {
						
					}

					@Override
					public void receiveResult(Object result) {
						System.out.println("receive result......");
						formatResult(params, exchange, (Object[]) result);
					}
				}, urlnum) {
    	protected void receive(int index, Object o) {
        if ((! done) && (! haveResult[index])) {
          haveResult[index] = true;
          if (o instanceof Exception) {
          	result[index] = null;
          } else {
          	result[index] = o;
          }

          try {
            if (isDone()) {
              done = true;
              parent.receiveResult(getResult());
            }
          } catch (Exception e) {
            done = true;
            parent.receiveException(e);
          }
        }
    	}
    };
		for (int i = 0; i < urls.length; ++i) {
			final String temp = urls[i] + urlParams[i];
			final WebPageQueryKey key = new WebPageQueryKey(urls[i], urlParams[i]);
      Continuation c = new NamedContinuation("Get page info " + i, multi.getSubContinuation(i));
			Metaweb.getInstance().getDhtApplication().lookup(key, c);
		}
		

	}

	@SuppressWarnings("restriction")
	protected void formatResult(HashMap<String,String> params, 
			HttpExchange exchange, Object[] resultList) {
		System.out.println("format");
		String temp = "";
		for (int i = 0; i < resultList.length; ++i) {
			if (resultList[i] != null) {
				WebPageQuery webpagequery = (WebPageQuery) resultList[i];
				NumberedPageRating rating = new NumberedPageRating(params.get("username"), webpagequery, i);
				temp += XMLMarshaller.getInstance().marshall(rating) + "\n";
				//System.out.println(XMLMarshaller.getInstance().marshall(rating));

			}
		}
		try {
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/xml");

			exchange.sendResponseHeaders(200, 0);

			OutputStream responseBody = exchange.getResponseBody();
			responseBody.write("<xmlresponse>".getBytes());
			
			if (temp.length() > 0) {
				responseBody.write(temp.getBytes());
			}

			responseBody.write("</xmlresponse>".getBytes());

			System.out.println(temp);
			responseBody.close();
			exchange.close();
			System.out.println("close get page rating bulk handler");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			exchange.close();
			System.out.println("close get page rating bulk handler");
		}
	}

}
